package my.download;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import my.download.pojo.Download12;
import my.download.util.ExcelUtils;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;


public class Application12 {

    private static final Logger log = LoggerFactory.getLogger(Application12.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) throws Exception {

        System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/" + "chromedriver.exe");
//        System.setProperty("webdriver.chrome.driver", "C:\\Users\\admin\\Desktop\\download-new/" + "chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://wwcs.hnzycfc.com:9000/#/login");
        log.info("请登录后输入1回车 ");
        Scanner sc = new Scanner(System.in);
        String input = sc.next();
        log.info(input);
        Set<Cookie> cookies = driver.manage().getCookies();
        String token = null;
        for (Cookie cookie : cookies) {
            if ("vue_admin_template_token_coll".equals(cookie.getName())) {
                token = cookie.getValue();
            }
        }
        driver.close();
        if (token == null) {
            log.warn("请登录");
            Thread.sleep(10 * 60 * 1000);
            return ;
        }
        String fileName = "导出-" + System.currentTimeMillis() + ".xlsx";
        String fullName = System.getProperty("user.dir") + "/" + fileName;
        Path path = Paths.get(fullName);
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(
                        PoolingHttpClientConnectionManagerBuilder.create().build()
                )
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectionRequestTimeout(60, TimeUnit.SECONDS)
                        .setResponseTimeout(60, TimeUnit.SECONDS)
                        .build()
                )
                .build();OutputStream out = Files.newOutputStream(path)) {

            String[][] headers = {
                    {"姓名", "name"},
                    {"身份证", "idCard"},
                    {"未收本金", "caseLoanBal"},
            };
            List<Download12> downloadList = download(httpClient, token);
            ExcelUtils.exportExcel2007(fileName, headers, downloadList, out);
        }
    }

    private static List<Download12> download(CloseableHttpClient httpClient, String token) {
        List<Download12> downloadList = new ArrayList<>();
        for (int i = 1; i < 1000; i++) {
            for (int j = 1; j < 3; ) {
                try {
                    List<Download12> list = download(httpClient, token, i);
                    downloadList.addAll(list);
                    if (list.size() < 100) {
                        return downloadList;
                    }
                    break;
                } catch (Exception e) {
                    log.info("error " + j, e);
                    j++;
                }
            }
            log.info("进度" + i);
        }
        return downloadList;
    }

    private static List<Download12> download(CloseableHttpClient httpClient, String token, int i) throws Exception {
        Map<String, Object> realData = new HashMap<>();
        realData.put("amount", null);
        realData.put("caseLoanBal", null);
        realData.put("days", null);
        realData.put("maxCaseAmt", null);
        realData.put("maxCaseLoanBal", null);
        realData.put("maxOverDays", null);
        realData.put("minCaseAmt", null);
        realData.put("minCaseLoanBal", null);
        realData.put("minOverDays", null);
        realData.put("bizType", "OUT");
        realData.put("orgCode", "100001004132");
        realData.put("page", i);
        realData.put("limit", 100);
        String str = executeReq(httpClient, "https://wwcs.hnzycfc.com:9000/fpi/coll/queue/list", token, realData, i);
        JsonNode jsonNodeList = objectMapper.readTree(str);
        List<Download12> downloadList = new ArrayList<>();
        for (JsonNode node : jsonNodeList) {
            downloadList.add(new Download12(node.get("custNamePlainText").asText(),
                    node.get("idNoPlainText").asText(),
                    node.get("caseLoanBal").asText()
                    )
            );
        }
        return downloadList;
    }

    private static String executeReq(CloseableHttpClient httpClient, String url, String token, Map<String, Object> realData, int i) throws Exception {
        String realDataStr = objectMapper.writeValueAsString(realData);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        String key = "9wsq6T1sHHnIHbXI";
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec("16-Bytes--String".getBytes(StandardCharsets.UTF_8)));
        byte[] encryptedBytes = cipher.doFinal(realDataStr.getBytes(StandardCharsets.UTF_8));
        Map<String, Object> data = new HashMap<>();
        data.put("apiCd", "100000");
        data.put("channelNo", "collweb");
        data.put("current", i);
        data.put("flowId", "8037296082cd11efa18ce3aff1fbc86b");
        data.put("pageSize", 100);
        data.put("path", "/mailbox/outQueueManage");
        data.put("sysId", "coll");
        data.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        data.put("version", "1.0");
        data.put("data", Base64.getEncoder().encodeToString(encryptedBytes));

        ClassicHttpRequest listReq = ClassicRequestBuilder.post(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36")
                .addHeader("Authtoken", token)
                .addHeader("Encryptkey", "wCZo5lC/SIN+0P5/gP7/0BQ1xSp89Gh6U5HiBw97QnxLn/0sHFmx/7Y1ZWqapJSYwrLicgBmYMNY3bJT3eBwPXWK4VmG7ibjhFGKhr3SzoOMBTYKggWxMJ9UlvZqlr8x798LGDqFVBFQ3OlIdLiPBKQH5gOvecpOlSi4G0g/dUB5GJ0bgMSzSDoJ8/jeFlBGgm2NRVsMzWC5pi6dntkhPIw8MdKBy7noUQArICVZUkStVOepcXTwLyJ3sHPSLEV3Gkgk/Y2RVKwx6CZ5lDWXVZDCkSfWNQ2iSTDx1N371AtpZIXRWkduoLJ13mKvmC6MnKDGfwzCAwYDTcW6oJUgmQ==")
                .setEntity(objectMapper.writeValueAsString(data), ContentType.APPLICATION_JSON)
                .build();
        String[] strArr = httpClient.execute(listReq, r -> {
            String respStr = EntityUtils.toString(r.getEntity());
            String serKey = r.getHeader("Encryptkey").getValue();
            return new String[]{respStr, serKey};
        });

        String aesKey = rsaDecrypt(strArr[1]);
        return aesDecrypt(objectMapper.readTree(strArr[0]).get("data").asText(), aesKey);
    }


    public static String aesDecrypt(String content, String password) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(Base64.getDecoder().decode(password), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(Base64.getDecoder().decode("1x1mASEW3tl8bG027HulAg=="));
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] original = cipher.doFinal(Base64.getDecoder().decode(content));
        return new String(original, StandardCharsets.UTF_8);
    }

    public static String rsaDecrypt(String content) throws Exception {
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, keyFactory.generatePrivate(pkcs8KeySpec));
        byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(content));
        return new String(bytes, StandardCharsets.UTF_8);
    }

    public static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy+6GFykwWsLc6sD17/fE" +
            "M3U0l9VwrIry+e8gqxlmK/SBtMuB3u8H9q33LyoGvT6IneW3iOv632w/416yf3Ht" +
            "QBSvyS3wuA3QcEZHDWLD7LBL/OhnMgmOSgj1bQAFjsV6ZyjqkP0jQySEG5ZJyqJ6" +
            "ZpBVKIIkTOajef2OzkkiBNqRUDvYysFZn5Sg8z7GGeYacfBLnDB5nmSjj+cZdsHI" +
            "wXFi6ZsqsF8rXRTb+YO0NbbrXGOWWjsI4efCrcshRODIXVIMk1AhJMUfX7S/xOEq" +
            "U6c9WJJGxIXASc1aE3iZ0eOWERU+m6sxePQxu+Iu2R8zdr3M4vlgKPAwDl5Enpqx" +
            "rQIDAQAB";

    public static String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC3+qYhNTMZDnSM1+gNuIN+qQAFrq8e9DEN2XV47b9Ge852ebsJxkMfcRnJLu5cyJLkok4GkijnuJ9AA6O618Opsn5JqBQA1PatKHIfHz5MJoTRQZvtlibpAJsX6XbzjGFhhMq7goOd+D3Ru0lg+Fn8p7FQIosYQkE0yLmOqe5egPdrvGRZSi8uujoyAUXwZ8QwA1cktnkEh8GV" +
            "m53+0DWNMCG2msJtb/2funXMfACjne+We6igSSA5zHzsbCZuEznmMR0u5i4Uius5" +
            "KXb4pO/zvJWqvXiQJggUdAOZsfujWOZE90SLkRw4U7nT+fpDgruDosL9P/rahufO" +
            "oYFYg0WdAgMBAAECggEAW/uHH8c3WumtP9WagXGk3KimCDFEANfZxrDYWLOVFCpG" +
            "GVnXN5XWbVvgpoM+TUlCl+jF1ecxaFkX1at8KqhBfRBur2jHR3syMXStSf4W6X/A" +
            "m9aPnQObRJc284eYH0AqV9VKfuFL6Kj6T2ex0jeY1gcJUaVTobdOXpOUok03jitX" +
            "LxOoCEW72TFqfOtYfZoRxo5hiI2g8qvictBZd6w8vf/KwdsjFUJFcCWiQPvEVqNc" +
            "Pij+cgvN4fqTToCRQ7arFqHZiGQb3JE78d+zh3Pdnnq204nxVw+dVHus01mK2JO0" +
            "pJrmmodtQwFTYTGtEzoHqDd3yIfiNguw7orGzS8KCQKBgQDlh0xSSK4MGvYA96gB" +
            "xhVGLOy/n/MrBhGcjpH02eXYauGe3KLb3pvm4xvw6Tsvcank41I1zehc4nwgstnj" +
            "glpBoUo97uZe9+UQhk61XURLFnM2Bd/Q+WRpG5sPYi7LpDc7w2I2NryjXpn0uHIi" +
            "YWKwFOblbpRt4evVZhPhB5Nk0wKBgQDNMoecNuk0Ci2Lgva7zkvvJ5rZZ+yHosML" +
            "/T/pbeAYJMF7Io0/A2sztDw+jOttN5S7cuH4fmLzhIAmZpM3ZvsHsoq1et1yEdd+" +
            "czJ4K+wc5njZxkSjcK8d5qKowEiWsH9Vh6IQHf+N8TD2M0IaQVtSl1pACDYdpwH+" +
            "D8TSfczlzwKBgQDi40Z3hC6/+pq4xBbIghUfhGMW3TbTjbE1D92JqydAMg8LKVC3" +
            "hSqZJmDFWNfPg00M3AS0+PC7eIp5DDLEaWNswtIPvKrur584IXuGXkaW7v8+JLpk" +
            "6VHvcIFryIM3fAG5St83dg4sc+Q9+2GfSKL0KgVAQHnq0Mt96+S0qfdyTwKBgAUI" +
            "4Frs3fvw4/0wUW16OlK73gjHi/4n+DErHY5Uq9Lr0/N5fY22P8MdAP1n577eRj/z" +
            "Kag3MaZX8ez/R01ssWwW7WBWi2hpF6h6mxpnuXtcDEsLmlOISEOrjQIm9aD846Lt" +
            "mQRcOBD7ggAIce7C+8KjBAveJ7XCi0H4kRO5EnXxAoGAb1YlA75TI+mg50gInk97" +
            "/Bepsr6pRG4d6K48YjNrglux7cJPaOewas7Hy/oVNaIf0HWSLgmtAE2irBIYgAI2" +
            "dfHFsYSgpvnEsIpAKl8WLM4CiZMOOhf90AMKUEszmtf1MnKyT/v4s1VQK//oWg40" +
            "RxlUBwcONI+c2dLM0tXO8jA=";
}
